using System;
using System.Collections.Generic;
using System.Text;
using Barrage.Global;

namespace Barrage.Meshes.Text
{
    /// <summary>
    /// Implements a singleton bitmap font cache with autoload functions
    /// </summary>
    public class BitmapFontManager : IDisposable
    {
        static BitmapFontManager instance = null;

        /// <summary>
        /// Returns the class instance.
        /// </summary>
        public static BitmapFontManager Fonts { get { if (instance == null) instance = new BitmapFontManager(); return instance; } }

        BitmapFontManager() { createDefaultFont();
        Engine.RegisterDisposeHandler(new EngineDisposeHandler(Dispose));
        }


        Dictionary<string, BitmapFont> fonts = new Dictionary<string, BitmapFont>();

        BitmapFont defaultFont;
        /// <summary>
        /// Returns the default font that's loaded when loaded fonts return error
        /// </summary>
        public static BitmapFont DefaultFont { get { return instance.defaultFont; } }

        /// <summary>
        /// Creates the default bitmap font
        /// </summary>
        protected void createDefaultFont()
        {
            defaultFont = new BitmapFont("Default");
        }

        /// <summary>
        /// Tries to load the font with the specified name
        /// </summary>
        /// <param name="name">font name</param>
        /// <returns>If everything went well, the loaded font. Else, the default font</returns>
        public BitmapFont this[string name]
        {
            get
            {
                BitmapFont f = null;
                if (fonts.TryGetValue(name, out f))
                    return f;
                NLog.LogManager.GetLogger(ToString()).Warn("Font " + name + " not found. Trying to load");
                try
                {
                    f = new BitmapFont(name);
                    NLog.LogManager.GetLogger(ToString()).Debug("Font " + name + " finished loading.");
                }
                catch
                {
                    NLog.LogManager.GetLogger(ToString()).Error("Error loading font " + name);
                    f = DefaultFont;
                }
                fonts.Add(name, f);
                return f;
            }
        }

        /// <summary>
        /// Clear resources
        /// </summary>
        public void Dispose()
        {
            foreach (BitmapFont bf in fonts.Values)
                bf.Dispose();
            fonts.Clear();
            defaultFont.Dispose();
            defaultFont = null;
            instance = null;
            NLog.LogManager.GetLogger(ToString()).Debug("Disposing");
            GC.SuppressFinalize(this);

            
        }

        /// <summary>
        /// Destructor. Clear resources
        /// </summary>
        ~BitmapFontManager()
        {
            Dispose();
        }

    }
}
